package com.financing.wap.web.controller.api;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.util.HttpClientPostUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("productVideoUrlController")
@RequestMapping("/api/getproductVideoUrl")
public class ProductVideoUrlController extends BaseController {
	
	/**
	 * 和讯视频获取地址
	 */
	private static String hxUrl = "http://v.ner98.com/index.php?getvideo=";
	
	@RequestMapping(value="")
	@ResponseBody
	public ResultMap getVideo(HttpServletRequest request,HttpServletResponse response,String videoOtherId){
		ResultMap result = new ResultMap();
		try{
			
			Session session = getSession();
			
			//未登录，返回未登录状态码
			if(!session.getLogin()){
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("statusCode", ResultMap.LOGIN_NOLOGIN_ERROR);
				return result;
			}
			
			if(StringUtil.isNullOrEmptyStr(videoOtherId)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				return result;
			}
			String userId = session.getUser().getId().toString();
			Map<String,String> param = new HashMap<String,String>();
			param.put("id", userId);
			//校验key
			param.put("vkey", getMD5Hex(userId));
			try {
				log.info("userId:"+userId+"  md5:"+param.get("vkey"));
				String responseStr = HttpClientPostUtil.HttpRequest(hxUrl+videoOtherId,param);
				log.info(responseStr);
				result.setAttribute("videoUrl",parseResponse(responseStr));
			} catch (Exception e) {
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("statusCode", ResultMap.STATUS_CODE_PROVIDEO_ERROR);
				log.error("get HX real url error!", e);
				return result;
			}
		}catch(Exception e){
			log.error("getVideo error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		return result;
	}
	
	/**
	 * 生成md5值
	 * @param str
	 * @return
	 * @throws Exception
	 */
	private String getMD5Hex(String str) throws Exception{
		byte[] tmp = MessageDigest.getInstance("MD5").digest((str+"hexunandsfa20160303").getBytes());
		StringBuilder sb = new StringBuilder();
		sb.append(byteArrayToHex(tmp));
//        for (byte b:tmp) {
//            sb.append(Integer.toHexString(b&0xff));
//        }
        System.out.println(sb.toString().length());
        return sb.toString();
	}
	
	/**
	 * 获取视频url
	 * @param result
	 * @return
	 */
	private String parseResponse(String result){
		JSONObject o = JSON.parseObject(result);
		String rs = o.getString("rs");
		if((!StringUtil.isNullOrEmptyStr(rs))&&(!"[]".equals(rs))){
			return JSON.parseObject(rs).getString("url");
		}
		return "";
	}
	
	public static String byteArrayToHex(byte[] byteArray) {  

        // 首先初始化一个字符数组，用来存放每个16进制字符  
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f' };  
        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））  
        char[] resultCharArray =new char[byteArray.length * 2];  
        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去  
        int index = 0; 
        for (byte b : byteArray) {  
           resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];  
           resultCharArray[index++] = hexDigits[b& 0xf];  
        }
        // 字符数组组合成字符串返回  
        return new String(resultCharArray);  
    }

	
	
	public static void main(String[] args) throws Exception {
		
		ProductVideoUrlController p = new ProductVideoUrlController();
		System.out.println(p.getMD5Hex("1118"));
		System.out.println(p.getMD5Hex("132"));
		JSONObject o = JSON.parseObject("{\"errorCode\":0,\"errorMessage\":\"\",\"rs\":{\"url\":\"http:\\/\\/v.ner98.com\\/d064a9c80248ea484714b2b343eac44b\\/leigen.mp4\"}}");
		System.out.println(JSON.parseObject(o.getString("rs")).get("url"));
	}
}
